package cn.cyb.server.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.util.Base64;
import java.util.Date;
import java.util.Map;

public class JwtUtils {

    public static final String secret = "2TyhheYx5EaXaxVywAVH1YA9e96PAbokHQRD5A/zTGn3t9pKRROXtggXKkLS1mP8qCdI6oUs2Y2Zp8JY8fyUhg==";

    /**
     * 从数据声明生成令牌生成token
     *
     * @param claims
     * @param expiration 过期时间
     * @return
     */
    public static String genToken(Map<String, Object> claims, Date expiration) {
        String token = Jwts.builder()
                .claims(claims) // 添加载荷
                .signWith(SignatureAlgorithm.HS512, secret) // 算法、秘钥
                .expiration(expiration)
                .compact();

        return token;
    }

    /**
     * 验证&解析token
     * token过期会抛异常
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        Jws<Claims> jws = Jwts.parser()
                .verifyWith(Keys.hmacShaKeyFor(Base64.getDecoder().decode(secret)))
                .build()
                .parseSignedClaims(token);
        Claims claims = jws.getPayload();
        return claims;
    }
}
